package com.sugree.twitter.views;

import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.StringItem;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
//#if polish.midp2 || polish.midp3
//# import javax.microedition.lcdui.Item;
//# import javax.microedition.lcdui.ItemCommandListener;
//#if project.HyperlinkList
//# import javax.microedition.lcdui.Choice;
//# import javax.microedition.lcdui.List;
//#endif
//#endif
import javax.microedition.lcdui.Displayable;

//#if polish.midp2 || polish.midp3
//# import com.substanceofcode.utils.StringUtil;
//#if project.HyperlinkList
//# import com.substanceofcode.utils.HttpUtil;
//#endif
//#endif
import com.substanceofcode.utils.Log;
import com.substanceofcode.twitter.model.Status;
import com.sugree.twitter.TwitterController;
import java.util.Vector;

//#if polish.midp2 || polish.midp3
//# public class StatusScreen extends Form implements CommandListener, ItemCommandListener {
//#else
public class StatusScreen extends Form implements CommandListener {
//#endif
	private TwitterController controller;

	private Status status;
	private int timeOffset;

        // este elemento es para poder trasldarse de un status a otro en la misma pantalla
        private Vector timeLine;
        private int indexTimeline;

//#if !(polish.midp2 || polish.midp3) || project.HyperlinkList
	private StringItem textField;
//#endif
	private Command replyCommand;
	private Command directCommand;
	private Command retweetCommand;
	private Command favoriteCommand;
	private Command backCommand;
        private Command nextCommand;
//#if polish.midp2 || polish.midp3
//# 	private Command linkCommand;
//#if project.HyperlinkList
//# 	private Command linkOpenCommand;
//# 	private Command linkBackCommand;
//# 	private List linkList;
//#endif
//#endif

	public StatusScreen(TwitterController controller) {
		super("");
		this.controller = controller;

//#if !(polish.midp2 || polish.midp3) || project.HyperlinkList
		textField = new StringItem("", "");
		append(textField);
//#endif

                nextCommand = new Command("Siguiente",Command.SCREEN,1);
                addCommand(nextCommand);
		backCommand = new Command("Atras", Command.BACK, 2);
		addCommand(backCommand);
		replyCommand = new Command("Responder", Command.SCREEN, 3);
		addCommand(replyCommand);
		retweetCommand = new Command("Compartir", Command.SCREEN, 3);
		addCommand(retweetCommand);
                /* ES UN CAMBIO NO NECESITAMOS ESTO
		favoriteCommand = new Command("Toggle Favorite", Command.SCREEN, 4);
		addCommand(favoriteCommand);
		directCommand = new Command("Direct Message", Command.SCREEN, 6);
		addCommand(directCommand);
                 *
                 */

//#if polish.midp2 || polish.midp3
//# 		linkCommand = new Command("Link", Command.SCREEN, 5);
//#if project.HyperlinkList
//# 		linkOpenCommand = new Command("Open", Command.ITEM, 1);
//# 		linkBackCommand = new Command("Cancel", Command.BACK, 2);
//# 		linkCommand = new Command("Link", Command.SCREEN, 5);
//# 		linkList = new List("Links", Choice.IMPLICIT);
//# 		linkList.setSelectCommand(linkOpenCommand);
//# 		linkList.addCommand(linkBackCommand);
//# 		linkList.setCommandListener(this);
//#endif
//#endif

		setCommandListener(this);
	}

	public void setTimeOffset(String offset) {
		try {
			int i = Integer.parseInt(offset);
			timeOffset = (i/100*3600+i%100*60)*1000;
		} catch (NumberFormatException e) {
			Log.error(e.toString());
		}
	}

        public void setTimeline(Vector timeline, int index){
            this.timeLine = timeline;
            this.indexTimeline = index;
            refreshStatus();
        }

        private void refreshStatus(){
            Status parStatus = (Status)this.timeLine.elementAt(this.indexTimeline);
            this.setStatus(parStatus);
        }

	public void setStatus(Status status) {
		this.status = status;
		setTitle(status.getScreenName());

                String text = status.getText()+"\n\n Tweet No."+this.indexTimeline;
		textField.setText(text);

                /*
		String favorited;
		if (status.getFavorited()) {
			favorited = " *";
		} else {
			favorited = "";
		}

		String interval;
		Date now = new Date();
		now.setTime(now.getTime()-controller.getServerTimeOffset());
                 * 
		Date date = new Date(status.getDate().getTime()+timeOffset);
		if (now.getTime() > date.getTime()) {
			interval = TimeUtil.getTimeInterval(date, now)+" ago";
		} else {
			interval = TimeUtil.getTimeInterval(now, date)+" in the future";
		}
                 *
                 */


//#if polish.midp2 || polish.midp3
//#if project.HyperlinkList
//# 		String text = status.getText()+"\n\nabout "+interval+" via "+status.getSource()+favorited;
//# 		textField.setText(text);
//# 
//# 		removeCommand(linkCommand);
//# 		linkList.deleteAll();
//# 
//# 		String chunks[] = StringUtil.split(status.getText(), " ");
//# 		String chunk;
//# 		for(int i=0; i<chunks.length; i++) {
//# 			chunk = chunks[i];
//# 			if (chunk.startsWith("http://") ||
//# 				chunk.startsWith("https://") ||
//# 				chunk.startsWith("www.")) {
//# 				if (!chunk.startsWith("http")) {
//# 					chunk = "http://"+chunk;
//# 				}
//# 				linkList.append(chunk, null);
//# 				handleTwitPic(chunk);
//# 			}
//# 		}
//# 		if (linkList.size() > 0) {
//# 			addCommand(linkCommand);
//# 		}
//#else
//# 		deleteAll();
//# 
//# 		javax.microedition.lcdui.StringItem si = null;
//# 		String chunks[] = StringUtil.split(status.getText(), " ");
//# 		String chunk;
//# 		for(int i=0; i<chunks.length; i++) {
//# 			chunk = chunks[i];
//# 			if (chunk.startsWith("http://") ||
//# 				chunk.startsWith("https://") ||
//# 				chunk.startsWith("www.")) {
//# 				si = new javax.microedition.lcdui.StringItem("", chunk,
//# 					javax.microedition.lcdui.Item.HYPERLINK);
//# 				si.setDefaultCommand(linkCommand);
//# 				si.setItemCommandListener(this);
//# 				append(si);
//# 			} else {
//# 				if (si == null || si.getAppearanceMode() == javax.microedition.lcdui.Item.HYPERLINK) {
//# 					si = new javax.microedition.lcdui.StringItem("", chunk);
//# 					append(si);
//# 				} else {
//# 					si.setText(si.getText()+" "+chunk);
//# 				}
//# 			}
//# 		}
//# 		si = new javax.microedition.lcdui.StringItem("", "\n");
//# 		si.setLayout(javax.microedition.lcdui.Item.LAYOUT_NEWLINE_BEFORE);
//# 		append(si);
//# 		si = new javax.microedition.lcdui.StringItem("",
//# 			"about "+interval+" via "+status.getSource()+favorited);
//# 		si.setLayout(javax.microedition.lcdui.Item.LAYOUT_NEWLINE_BEFORE);
//# 		append(si);
//#endif
//#else
		// String text = status.getText()+"\n\nabout "+interval+" via "+status.getSource()+favorited;

//#endif
	}

//#if polish.midp2 || polish.midp3
//# 	public void commandAction(Command cmd, javax.microedition.lcdui.Item item) {
//# 		String url = ((javax.microedition.lcdui.StringItem)item).getText();
//# 		if (!url.startsWith("http")) {
//# 			url = "http://"+url;
//# 		}
//# 		controller.openUrl(url);
//# 		Log.info("open "+url);
//# 	}
//#endif

	public void commandAction(Command cmd, Displayable display) {
		if (cmd == backCommand) {
			status = null;
			controller.showTimeline();
		} else if (cmd == replyCommand) {
			controller.showUpdate("@"+status.getScreenName()+" ");
			controller.setReplyTo(status.getId());
		} else if (cmd == directCommand) {
			controller.showUpdate("d "+status.getScreenName()+" ");
		} else if (cmd == retweetCommand) {
			controller.showUpdate(status.getRetweet(controller.getStatusMaxLength()));
                } else if (cmd == nextCommand) {
                        // Luis Fernando Muñoz, agregamos el comando proximo tweet
                        if (this.indexTimeline >= 0) {
                            this.indexTimeline = this.indexTimeline-1;
                            this.refreshStatus();
                        } else {
                            this.indexTimeline = this.timeLine.size()-1;
                        }
		} else if (cmd == favoriteCommand) {
			// controller.toggleFavorited(status);
//#if (polish.midp2 || polish.midp3) && project.HyperlinkList
//# 		} else if (cmd == linkCommand) {
//# 			controller.showList(linkList);
//# 		} else if (cmd == linkOpenCommand) {
//# 			String url = linkList.getString(linkList.getSelectedIndex());
//# 			controller.showStatus(status);
//# 			/*
//# 			Log.info("open "+url);
//# 			if (url.startsWith("http://twitpic.com/") && url.endsWith(".jpg")) {
//# 				try {
//# 					url = HttpUtil.getLocation(url, "");
//# 				} catch (Exception e) {
//# 					Log.error("TwitPic "+e.toString());
//# 				}
//# 			}
//# 			*/
//# 			Log.info("open "+url);
//# 			controller.openUrl(url);
//# 		} else if (cmd == linkBackCommand) {
//# 			controller.showStatus(status);
//#endif
		}
	}

//#ifdef polish.usePolishGui
//# 	public void keyPressed(int code) {
//# 		switch (code) {
//# 		case Canvas.KEY_NUM4: // reply
//# 			controller.showUpdate("@"+status.getScreenName()+" ");
//# 			controller.setReplyTo(status.getId());
//# 			break;
//# 		case Canvas.KEY_NUM6: // direct
//# 			controller.showUpdate("d "+status.getScreenName()+" ");
//# 			break;
//# 		case Canvas.KEY_NUM5: // retweet
//# 			controller.showUpdate(status.getRetweet(controller.getStatusMaxLength()));
//# 			break;
//# 		case Canvas.KEY_NUM7: // delete, as Gmail mobile
//# 			break;
//# 		case Canvas.KEY_STAR: // favorite, as Gmail mobile
//# 			controller.toggleFavorited(status);
//# 			break;
//# 		default:
			//# super.keyPressed(code);
//# 			break;
//# 		}
//# 	}
//#endif

//#if (polish.midp2 || polish.midp3) && project.HyperlinkList
//# 	public void handleTwitPic(String url) {
//# 		String orig = url;
//# 		if (url.startsWith("https://")) {
//# 			url = url.substring(8);
//# 		}
//# 		if (url.startsWith("http://")) {
//# 			url = url.substring(7);
//# 		}
//# 		if (url.startsWith("www.")) {
//# 			url = url.substring(4);
//# 		}
//# 		int slash = url.indexOf('/');
//# 		if (slash >= 0) {
//# 			String host = url.substring(0, slash);
//# 			String path = url.substring(slash+1, url.length());
//# 			if (host.equals("twitpic.com") && path.indexOf('/') == -1) {
//# 				linkList.append("http://twitpic.com/show/thumb/"+path+".jpg", null);
//# 			} else if ((host.equals("pic.gd") || host.equals("tweetphoto.com")) && path.indexOf('/') == -1) {
//# 				linkList.append("http://TweetPhotoAPI.com/api/TPAPI.svc/imagefromurl?size=thumbnail&url="+orig, null);
//# 			}
//# 		}
//# 	}
//#endif
}
